設計中秋卡片應用程式,練習用Compose LazyColumn ,我要一次來十個圖文
data class Congratulations(
@StringRes val stringResourceId: Int,
@DrawableRes val imageResourceId: Int
)
class Datasource() {
fun loadCongratulations(): List<Congratulations> {
return listOf<Congratulations>(
Congratulations(R.string.congratulatory_msg1, R.drawable.moon_1),
...
Congratulations(R.string.congratulatory_msg10, R.drawable.moon_10))
}
}
@Composable
fun CongratulationsCard(congratulation: Congratulations, modifier: Modifier = Modifier) {
Card(modifier = modifier) {
Column {
Image(
painter = painterResource(congratulation.imageResourceId),
contentDescription = stringResource(congratulation.stringResourceId),
modifier = Modifier,
contentScale = ContentScale.FillWidth
)
Text(
text = LocalContext.current.getString(congratulation.stringResourceId),
modifier = Modifier.padding(16.dp),
style = MaterialTheme.typography.headlineSmall
)
}
}
}
@Preview
@Composable
private fun CongratulationsCardPreview() {
CongratulationsCard(Congratulations(R.string.congratulatory_msg1, R.drawable.moon_1))
}
使用 LazyColumn 可組合函式建立可捲動的清單。
@Composable
fun CongratulationsList(congratulationsList: List<Congratulations>, modifier: Modifier = Modifier) {
LazyColumn(modifier = modifier) {
items(congratulationsList) { congratulation ->
CongratulationsCard(
congratulation = congratulation,
modifier = Modifier.padding(8.dp)
)
}
}
}
@Preview(showBackground = true)
@Composable
fun CongratulationsListAppPreview() {
Ironman2024Theme {
CongratulationsListApp(Modifier)
}
}